// Logistics/DamageDetail/DamageDetail.js
/*{
单元名称：货损详情页面js
单元功能：选择销售单列出货物列表，录入货损数量，上传图片提交
所属模块功能：
创建人：yan
创建时间：230905
修改人：
修改时间：
}*/
let logisticsBehavior = require('../behavior/logistics')
Page({
  behaviors: [logisticsBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    orderid: '1000108',

    //当前选择行
    activeTr: 0,
    //当前编辑行
    editTr: -1,
    //编辑标识
    isEdit: false,

    field: [
      {type: 'picture',field_id: 'pic1',label: '照片1',picCount: 20},
    ],

    // 照片列表
    picList: [],


  },
  components: {

  },
  //选择销售单
  selectSales(e){
    let {index} = e.currentTarget.dataset,
      {salesOrder} = this.data;
    // 选择销售单，获取货损列表
    this.setData({
      activeTr: index
    });
    this.getGoodsDamage(salesOrder[index].row_id);
  },
  //修改货损
  toggleEditStatus(e){
    let {index} = e.currentTarget.dataset,
    {activeTr, editTr,salesOrder} = this.data,
      obj = {editTr: index};
    if (editTr === index){
      obj = {editTr: -1, isEdit: false}
    } else {
      obj = {editTr: index,isEdit: true}
      //当前编辑行非当前显示行则重新获取货物列表进行编辑
      if (index !== -1 && index !== activeTr){
        obj.activeTr = index;
        //  获取货损
        this.getGoodsDamage(salesOrder[index].row_id);
      }
    }
    this.setData(obj)
  },

  // 货物列表数量修改
  bindipt(e){
    let {index} = e.currentTarget.dataset,
      {value} = e.detail;
    this.setData({
      [`goodsList[${index}].huosunshuliang`]: value
    })
  },

  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val,
      val2 = '',
      obj = this.data.inputData;

    if (type === 'num' || type === 'currency' || type === 'percent'){
      val = val ? val : null
    }
    if (id === 'pic1'){
      let picList = val && val.split(',') || [];

      this.setData({picList})
    }

    //赋值
    this.data.inputData[id] = val;

  },


  //获取运单管理明细（销售单）
  getSalesDamage(id){
    let url = `WLAuth/XiaoShouChuKuDan/${id}`;
    wx.showLoading({mask: true})
    wx.$get(5,url).then(res => {
      if (res.errcode != 0) return;
      let data = res.data.row || [];
      this.setData({salesOrder: data});
      if (data[0]){
        this.getGoodsDamage(data[0].row_id)
      }else {
        wx.hideLoading();
      }
    })
  },
  //获取货损货物 id：运单管理明细id
  getGoodsDamage(id){
    // let url = `WLAuth/HuoSunXiaoShouDanHuoWu/${id}`;
    let url = `WLAuth/HunSunHuoWu/XiaoShouDan/${id}`;
    wx.showLoading({mask: true})
    wx.$get(5,url).then(res => {
      if (res.errcode != 0) return;
      let data = res.data.row || [];
      this.setData({goodsList: data});
      wx.hideLoading();
    })
  },

  //提交
  onSubmit(){
    wx.showLoading({mask: true});
    this.submitDamage().then(res => {
      this.submitFollow().then(() => {
        wx.$toast('修改成功');
      })
    })
  },

  //提交货损
  submitDamage(){
    return new Promise(resolve => {
      let {goodsList,salesOrder,activeTr} = this.data,
        id = salesOrder[activeTr].row_id,
        arr = [];
      goodsList.forEach(item => {
        arr.push({
          "yundanhuowu_id": item.huosunwu,
          "huosunshuliang": item.huosunshuliang
        })
      });
      let url = `WLAuth/HuoSun/${id}`;
      wx.$post(5,url,arr).then(res => {
        if (res.errcode != 0) return;
        resolve(res.data.row && res.data.row[0]);
      })
    })

  },
  //提交跟踪记录
  submitFollow(){
    return new Promise(resolve => {
      let {orderid } = this.data,
        url2 = `WLAuth/HuoSunTuPian?yundanhao=${orderid}`; //提交货损照片

      let {picList} = this.data,
        pics = [];
      //循环把图片列表分成每5张图片一个数组
      for (let i = 0; i < picList.length; i += 5) {
        pics.push(picList.slice(i, i + 5));
      }
      let post2 = {},
        tp = ['tupian1','tupian2','tupian3','tupian4','tupian5']; //货损图片传入参数
      for (let i = 0;i < 5;i++){
        post2[tp[i]] = pics[i] && pics[0].join(',') || '';
      }

       wx.$post(5,url2,post2).then(res => {
         if (res.errcode != 0) return;
         resolve();
       })
    })
  },

  init(){
    let yundanxinxi = wx.getStorageSync('yundanxinxi');
    wx.removeStorageSync('yundanxinxi');
    let {tupian1,tupian2,tupian3,tupian4,tupian5,} = yundanxinxi,
      arr = [];
    tupian1 && arr.push(tupian1);
    tupian2 && arr.push(tupian2);
    tupian3 && arr.push(tupian3);
    tupian4 && arr.push(tupian4);
    tupian5 && arr.push(tupian5);
    let pics = arr.join(',');
    // pics = pics && pics.split(',');
    this.setData({
      ['inputData.pic1']: pics
    })

  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {transitorderid,orderid} = options;
    this.setData({transitorderid,orderid});
    this.getSalesDamage(orderid);
    this.init();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
